<template>
    <el-switch
        v-model="paramValue"
        :active-text="activeText"
        :inactive-text="inactiveText"
        :active-color="activeColor"
        :inactive-color="inactiveColor"
        @change="change"
    ></el-switch>
</template>
<script>
import { getValue, getParam, updateParam } from "common/src/api/commonParam";

export default {
    name: "ParamSwitch",
    model: {
        prop: "paramValue",
        event: "change"
    },
    props: [
        "paramValue",
        "code",
        "activeText",
        "inactiveText",
        "activeColor",
        "inactiveColor"
    ],
    mounted() {
        this.getValue();
    },
    data() {
        return {};
    },
    methods: {
        getValue() {
            var that = this;
            getValue(this.code).then(res => {
                if (res.code === 200) {
                    if (typeof res.data == "boolean") {
                        this.paramValue = res.data;
                        this.$emit("change", res.data); // 获取到数据也执行change 好让父组件获取数据
                    } else {
                        this.$message({
                            type: "error",
                            message: "参数开关只能用于布尔型参数"
                        });
                    }
                } else {
                    this.$message({
                        type: "error",
                        message: res.msg
                    });
                }
            });
        },
        change(value) {
            updateParam(this.code, { value })
                .then(res => {
                    if (res.code == 200) {
                        console.log(111);
                        this.$emit("change", value); // 当且仅当获取到修改数据后才会执行change事件
                    } else {
                        this.paramValue = !value;
                    }
                })
                .catch(res => {
                    this.paramValue = !value;
                });
        }
    }
};
</script>
